package sharewithus.business.service.impl;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import magick.ImageInfo;
import magick.MagickImage;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.util.WebUtils;

import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import sharewithus.business.dao.IUserDAO;
import sharewithus.business.dto.UserExtDTO;
import sharewithus.business.dto.UserIntegralDTO;
import sharewithus.business.dto.UserParamDTO;
import sharewithus.business.service.UserService;
import sharewithus.common.Common;
import sharewithus.utils.UserUtil;

import com.thoughtworks.xstream.XStream;

import framelib.common.FrameCommon;
import framelib.common.SessionData;
import framelib.exception.SystemException;
import framelib.mq.SpringJmsProducer;
import framelib.service.AbsService;
import framelib.utils.ClientXmemcached;
import framelib.utils.DataUtils;
import framelib.utils.DateUtil;
import framelib.utils.FileUtils;
import framelib.utils.MainUtil;
import framelib.utils.PropReader;
import framelib.utils.ThreadLocalUtil;


/**
 * Title:UserServiceImpl
 * Description:
 * @Create_by:Vince Yu
 * @Create_date:2012-5-4
 * @Last_Edit_By:
 * @Edit_Description
 * @version:partynano 1.0
 * 
 */
@SuppressWarnings("unchecked")
public class UserServiceImpl extends AbsService implements UserService {

	@Autowired
	@Qualifier("userDAO")
	IUserDAO userDAO;
	
	@Autowired
	@Qualifier("userDAOQ")
	IUserDAO userDAOQ;

	@Autowired
	@Qualifier("clientMemcached")
	ClientXmemcached mc;

	@Autowired
	@Qualifier("producer")
	SpringJmsProducer producer;
	
	@Autowired
	@Qualifier("shardedJedisPool")
	private ShardedJedisPool jedisPool;

	public void saveRefererUrlNN(HttpServletRequest request) throws Exception{
		WebUtils.setSessionAttribute(request, Common.REFERER_URL, request.getHeader("referer"));
	}
	
	public String getRefererUrlNN(HttpServletRequest request) throws Exception{
		return String.valueOf(WebUtils.getSessionAttribute(request, Common.REFERER_URL));
	}
	
	public void registeUser(
			String email,
			String nickname,
			String password,
			String passStrength,
			String sex,
			String province,
			String city,
			String county,
			String birthYear,
			String birthMonth,
			String birthDay) throws Exception{
		if(!DataUtils.allNotBlank(email)){throw new SystemException("isNull",new Object[]{email});}
		if(!DataUtils.allNotBlank(nickname)){throw new SystemException("isNull",new Object[]{nickname});}
		if(!DataUtils.allNotBlank(password)){throw new SystemException("isNull",new Object[]{password});}
		else{password = DataUtils.getMD5Str(password);}
		if(!DataUtils.allNotBlank(passStrength)){throw new SystemException("isNull",new Object[]{passStrength});}
		if(!DataUtils.allNotBlank(sex)){throw new SystemException("isNull",new Object[]{sex});}
		if(!DataUtils.allNotBlank(province)){throw new SystemException("isNull",new Object[]{province});}
		if(!DataUtils.allNotBlank(city)){throw new SystemException("isNull",new Object[]{city});}
		if(!DataUtils.allNotBlank(county)){throw new SystemException("isNull",new Object[]{county});}
		if(!DataUtils.allNotBlank(birthYear)){throw new SystemException("isNull",new Object[]{birthYear});}
		if(!DataUtils.allNotBlank(birthMonth)){throw new SystemException("isNull",new Object[]{birthMonth});}
		if(!DataUtils.allNotBlank(birthDay)){throw new SystemException("isNull",new Object[]{birthDay});}
		int userId = 0;
		try{
			userId = userDAO.saveUser(email, nickname, password, passStrength, email, DateUtil.getSystemTime());
		}catch (Exception e) {
			throw new SystemException("userSave");
		}
		
		List userExts = UserUtil.getUserExt();
		for(int i = 0; i<userExts.size(); i++){
			UserExtDTO uet = new UserExtDTO();
			uet = (UserExtDTO)userExts.get(i);
			String paramName = uet.getParamName();
			String extId = uet.getId();
			String extValue = "";
			//与ExtValue.properties顺序相同,也就是与保存顺序相同
			if(paramName.equalsIgnoreCase("sex")){
				extValue = sex;
			}else if(paramName.equalsIgnoreCase("province")){
				extValue = province;
			}else if(paramName.equalsIgnoreCase("city")){
				extValue = city;
			}else if(paramName.equalsIgnoreCase("county")){
				extValue = county;
			}else if(paramName.equalsIgnoreCase("birthday")){
				extValue = birthYear+"-"+birthMonth+"-"+birthDay;
			}
			try{
				userDAO.saveUserExt(userId, Integer.parseInt(extId), extValue, FrameCommon.PNN_FLAG_TRUE, FrameCommon.PNN_FLAG_TRUE, DateUtil.getSystemTime());
			}catch (Exception e) {
				throw new SystemException("userSaveExt");
			}
			
		}
	}
	
	public boolean checkUserNN(
			String nickname,
			HttpServletRequest request) throws Exception{
		if(WebUtils.getSessionAttribute(request, FrameCommon.PNN_SESSION) == null){
			return userDAOQ.getUserBy(nickname, "nickname") == null?true:false;
		}else{
			String sessionName = ((SessionData)WebUtils.getSessionAttribute(request, FrameCommon.PNN_SESSION)).getNickName();
			if(nickname.equalsIgnoreCase(sessionName)){
				return true;
			}else{
				return userDAOQ.getUserBy(nickname, "nickname") == null?true:false;
			}
		}
	}
	
	public boolean checkEmailNN(
			String email,
			HttpServletRequest request) throws Exception{
		if(WebUtils.getSessionAttribute(request, FrameCommon.PNN_SESSION) == null){
			return userDAOQ.getUserBy(email, "email") == null?true:false;
		}else{
			String sessionName = ((SessionData)WebUtils.getSessionAttribute(request, FrameCommon.PNN_SESSION)).getEmail();
			return email.equalsIgnoreCase(sessionName)?true:false;
		}
	}
	
	public boolean checkPassword(
			String userName,
			String password,
			HttpServletRequest request) throws Exception{
		SessionData session = new SessionData();
		if(!DataUtils.allNotBlank(userName)){throw new SystemException("isNull",new Object[]{userName});}
		Map res = (Map<String, Object>)userDAOQ.getUserBy(userName, "nickname");
		if(res == null || res.get("email") == null || res.get("id") == null || res.get("nickname") == null){
			throw new SystemException("userLoginPassword");
		}
		boolean suc = DataUtils.getMD5Str(password).equalsIgnoreCase(res.get("password").toString());
		if(suc == false){
			throw new SystemException("userLoginPassword");
		}else{
			session.setEmail(String.valueOf(res.get("email")));
			session.setId(Integer.parseInt(String.valueOf(res.get("id"))));
			session.setNickName(String.valueOf(res.get("nickname")));
			session.setAvatar(String.valueOf(res.get("avatar")));
			session.setPassStrength(String.valueOf(res.get("pass_strength")));
			session.setSecurityEmail(String.valueOf(res.get("security_email")));
			session.setLastLoginIp(String.valueOf(res.get("last_login_ip")));
			session.setLastLoginTime(String.valueOf(res.get("last_login_time")));
			
			List userExts = userDAOQ.getUserExtBy(res.get("id").toString(), "userId");
			for(int i = 0; i<userExts.size(); i++){
				Map userExt = (HashMap)userExts.get(i);
				UserParamDTO up = new UserParamDTO();
				up.setExtValue(userExt.get("ext_value")==null?"":String.valueOf(userExt.get("ext_value")));
				up.setFlag(userExt.get("flag")==null?0:Integer.parseInt(String.valueOf(userExt.get("flag"))));
				up.setIndexNo(userExt.get("index_no")==null?0:Integer.parseInt(String.valueOf(userExt.get("index_no"))));
				up.setLableName(userExt.get("lable_name")==null?"":String.valueOf(userExt.get("lable_name")));
				up.setParamName(userExt.get("param_name")==null?"":String.valueOf(userExt.get("param_name")));
				up.setPermission(userExt.get("permission")==null?0:Integer.parseInt(String.valueOf(userExt.get("permission"))));
				up.setType(userExt.get("type")==null?"":String.valueOf(userExt.get("type")));
				session.getUserParams().add(up);
			}
			
			session.setCurrentLoginIp(MainUtil.getIp(request));
			session.setCurrentLoginTime(DateUtil.getSystemTime("second"));
			WebUtils.setSessionAttribute(request, FrameCommon.PNN_SESSION, session);
			ThreadLocalUtil.setSession(session);
			mc.add(session.getId()+FrameCommon.PNN_SESSION, session);
		}
		return true;
	}
	
	
	public void userLogout(
			HttpServletRequest request) throws Exception{
		request.getSession().invalidate();
	}
	
	
	public void updateUserInfo(
			String userId,
			String email,
			String nickname,
			String sex,
			String province,
			String city,
			String county,
			String birthYear,
			String birthMonth,
			String birthDay,
			HttpServletRequest request) throws Exception{
		if(!DataUtils.allNotBlank(email)){throw new SystemException("isNull",new Object[]{email});}
		if(!DataUtils.allNotBlank(nickname)){throw new SystemException("isNull",new Object[]{nickname});}
		if(!DataUtils.allNotBlank(sex)){throw new SystemException("isNull",new Object[]{sex});}
		if(!DataUtils.allNotBlank(province)){throw new SystemException("isNull",new Object[]{province});}
		if(!DataUtils.allNotBlank(city)){throw new SystemException("isNull",new Object[]{city});}
		if(!DataUtils.allNotBlank(county)){throw new SystemException("isNull",new Object[]{county});}
		if(!DataUtils.allNotBlank(birthYear)){throw new SystemException("isNull",new Object[]{birthYear});}
		if(!DataUtils.allNotBlank(birthMonth)){throw new SystemException("isNull",new Object[]{birthMonth});}
		if(!DataUtils.allNotBlank(birthDay)){throw new SystemException("isNull",new Object[]{birthDay});}
		try{
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("userId", Integer.parseInt(userId));
		    param.put("email", email);
		    param.put("nickname", nickname);
			userDAO.updateUser(param);
		}catch (Exception e) {
			throw new SystemException("userSave");
		}
		
		List userExts = UserUtil.getUserExt();
		userDAO.deleteUserExt(Integer.parseInt(userId));
		SessionData session = new SessionData();
		session.setEmail(email);
		session.setNickName(nickname);
		for(int i = 0; i<userExts.size(); i++){
			UserExtDTO uet = new UserExtDTO();
			UserParamDTO up = new UserParamDTO();
			uet = (UserExtDTO)userExts.get(i);
			String paramName = uet.getParamName();
			String extId = uet.getId();
			String extValue = "";
			//与ExtValue.properties顺序相同,也就是与保存顺序相同
			if(paramName.equalsIgnoreCase("sex")){
				extValue = sex;
				up.setExtValue(extValue);
				up.setFlag(FrameCommon.PNN_FLAG_TRUE);
				up.setIndexNo(Integer.parseInt(uet.getIndexNo()));
				up.setLableName(uet.getLableName());
				up.setParamName(uet.getParamName());
				up.setPermission(FrameCommon.PNN_FLAG_TRUE);
				up.setType(uet.getType());
			}else if(paramName.equalsIgnoreCase("province")){
				extValue = province;
				up.setExtValue(extValue);
				up.setFlag(FrameCommon.PNN_FLAG_TRUE);
				up.setIndexNo(Integer.parseInt(uet.getIndexNo()));
				up.setLableName(uet.getLableName());
				up.setParamName(uet.getParamName());
				up.setPermission(FrameCommon.PNN_FLAG_TRUE);
				up.setType(uet.getType());
			}else if(paramName.equalsIgnoreCase("city")){
				extValue = city;
				up.setExtValue(extValue);
				up.setFlag(FrameCommon.PNN_FLAG_TRUE);
				up.setIndexNo(Integer.parseInt(uet.getIndexNo()));
				up.setLableName(uet.getLableName());
				up.setParamName(uet.getParamName());
				up.setPermission(FrameCommon.PNN_FLAG_TRUE);
				up.setType(uet.getType());
			}else if(paramName.equalsIgnoreCase("county")){
				extValue = county;
				up.setExtValue(extValue);
				up.setFlag(FrameCommon.PNN_FLAG_TRUE);
				up.setIndexNo(Integer.parseInt(uet.getIndexNo()));
				up.setLableName(uet.getLableName());
				up.setParamName(uet.getParamName());
				up.setPermission(FrameCommon.PNN_FLAG_TRUE);
				up.setType(uet.getType());
			}else if(paramName.equalsIgnoreCase("birthday")){
				extValue = birthYear+"-"+birthMonth+"-"+birthDay;
				up.setExtValue(extValue);
				up.setFlag(FrameCommon.PNN_FLAG_TRUE);
				up.setIndexNo(Integer.parseInt(uet.getIndexNo()));
				up.setLableName(uet.getLableName());
				up.setParamName(uet.getParamName());
				up.setPermission(FrameCommon.PNN_FLAG_TRUE);
				up.setType(uet.getType());
			}
			
			session.getUserParams().add(up);
			
			try{
				userDAO.saveUserExt(Integer.parseInt(userId), Integer.parseInt(extId), extValue, FrameCommon.PNN_FLAG_TRUE, FrameCommon.PNN_FLAG_TRUE, DateUtil.getSystemTime());
			}catch (Exception e) {
				throw new SystemException("userSaveExt");
			}
		}
		
		WebUtils.setSessionAttribute(request, FrameCommon.PNN_SESSION, session);
		mc.add(session.getId()+FrameCommon.PNN_SESSION, session);
	}
	
	
	public Map uploadUserAvatar(
			HttpServletRequest request) throws Exception{
		Map res = new HashMap();
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查输入请求是否为multipart表单数据。
	    if (isMultipart == true) {
	       FileItemFactory factory = new DiskFileItemFactory();//为该请求创建一个DiskFileItemFactory对象，通过它来解析请求。执行解析后，所有的表单项目都保存在一个List中。
	       ServletFileUpload upload = new ServletFileUpload(factory);
	       List<FileItem> items = new ArrayList<FileItem>();
	        try {
		        items = upload.parseRequest(request);
		        Iterator<FileItem> itr = items.iterator();
		        String fileName = "";
		        while (itr.hasNext()) {
		           FileItem item = (FileItem) itr.next();
		           //检查当前项目是普通表单项目还是上传文件。
		           if (item.isFormField()) {//如果是普通表单项目，显示表单内容。
				       
		           } else {//如果是上传文件，显示文件名。
				       String filename=new String(item.getName().getBytes(), "gb2312"); 
				       String imgStyle = filename.split("\\.")[filename.split("\\.").length - 1];	
				       if(!imgStyle.equals("jpg") && !imgStyle.equals("jpeg") && !imgStyle.equals("JPG") && !imgStyle.equals("JPEG")) {
				   			res.put("error", "type");
				   			break;
						}
				       filename = filename.substring(0,filename.indexOf("."))+ DateUtil.getSystemTime4Name() +"."+imgStyle;
			           File savefile=new File(new PropReader(FrameCommon.PNN_GLOBAL_CONFIG).getString(Common.PNN_USER_AVATAR_CONFIG_KEY)+filename);
			           fileName = savefile.getName();
			           if(FileUtils.FormetFileSize(FileUtils.getFileSizes(savefile)) > Common.PNN_IMAGE_MAX_SIZE) {
			        	   res.put("error", "large");
			        	   break;
						}
				   		BufferedImage sourceImg = javax.imageio.ImageIO.read(item.getInputStream());
				   		if(sourceImg.getWidth()>=sourceImg.getHeight()){
				   			if(sourceImg.getWidth() >= 400){
					   			res.put("width", 400);
					   		}else{
					   			res.put("width", sourceImg.getWidth());
					   			res.put("height", "auto");
					   		}
				   		}else{
				   			if(sourceImg.getHeight() >= 400){
					   			res.put("height", 400);
					   		}else{
					   			res.put("height", sourceImg.getHeight());
					   			res.put("width", "auto");
					   		}
				   		}
				   		
			           fileName = savefile.getName();
	                   item.write(savefile);
		           }
			        
		           res.put("fileName", fileName);
		       }
	        } catch (FileUploadException e) {
		        // TODO Auto-generated catch block
		        e.printStackTrace();
	        }  catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
	    }
		return res;
	}
	
	
	public void saveUserAvatar(String filePath,
    		int x1,
    		int y1,
    		int x2,
    		int y2,
    		int w,
    		int h,
			HttpServletRequest request) throws Exception{
		ImageInfo infoS = null;
        MagickImage cropped = null;
        MagickImage avatar_large = null;
        MagickImage avatar_mid = null;
        MagickImage avatar_small = null;
        File source = new File(new PropReader(FrameCommon.PNN_GLOBAL_CONFIG).getString(Common.PNN_USER_AVATAR_CONFIG_KEY)+ filePath);
        BufferedImage sourceImg = javax.imageio.ImageIO.read(new FileInputStream(source));
        
        int imgW = sourceImg.getWidth();
        int imgH = sourceImg.getHeight();
        
        double p = 0.0;
        if(imgW >= imgH){
        	if(imgW >= 400){
        		p = (double)imgW / 400.0;
        	}
        }else{
        	if(imgH >= 400){
        		p = (double)imgH / 400.0;
        	}
        }
        
		int x = (int)(x1*p);
		int y = (int)(y1*p);
		int width = (int)(w*p);
		int height = (int)(h*p);
        Rectangle rec = new Rectangle(x, y, width, height);
        try {
            infoS = new ImageInfo(source.getPath());
            cropped = new MagickImage(infoS);
            //裁切缩放后图片
            cropped = cropped.cropImage(rec);
            avatar_large = cropped.scaleImage(180, 180);
            avatar_large.setFileName(new PropReader(FrameCommon.PNN_GLOBAL_CONFIG).getString(Common.PNN_USER_AVATAR_SAVE_LARGE_CONFIG_KEY)+ filePath + "");
            avatar_mid = cropped.scaleImage(50, 50);
            avatar_mid.setFileName(new PropReader(FrameCommon.PNN_GLOBAL_CONFIG).getString(Common.PNN_USER_AVATAR_SAVE_MID_CONFIG_KEY)+ filePath + "");
            avatar_small = cropped.scaleImage(30, 30);
            avatar_small.setFileName(new PropReader(FrameCommon.PNN_GLOBAL_CONFIG).getString(Common.PNN_USER_AVATAR_SAVE_SMALL_CONFIG_KEY)+ filePath + "");
            avatar_large.writeImage(infoS);
            avatar_mid.writeImage(infoS);
            avatar_small.writeImage(infoS);
        } finally {
	        if (cropped != null) {
	            cropped.destroyImages();
	        }
        }
        
        String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
        SessionData sd = ((SessionData)WebUtils.getSessionAttribute(request, FrameCommon.PNN_SESSION));
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", sd.getId());
	    param.put("avatar", fileName);
        userDAO.updateUser(param);
        sd.setAvatar(fileName);
        WebUtils.setSessionAttribute(request, FrameCommon.PNN_SESSION, sd);
	}
	
	
	public Map initPersionPage(String userName, 
			HttpServletRequest request) throws Exception{
		Map page = new HashMap();
		Map res = (Map<String, Object>)userDAOQ.getUserBy(userName, "nickname");
		SessionData person = new SessionData();
		if(res != null && res.get("id")!= null){
			List userExts = userDAOQ.getUserExtBy(res.get("id").toString(), "userId");
			person = new SessionData();
			person.setEmail(String.valueOf(res.get("email")));
			person.setId(Integer.parseInt(String.valueOf(res.get("id"))));
			person.setNickName(String.valueOf(res.get("nickname")));
			person.setAvatar(String.valueOf(res.get("avatar")));
			
			for(int i = 0; i<userExts.size(); i++){
				Map userExt = (HashMap)userExts.get(i);
				UserParamDTO up = new UserParamDTO();
				up.setExtValue(userExt.get("ext_value")==null?"":String.valueOf(userExt.get("ext_value")));
				up.setFlag(userExt.get("flag")==null?0:Integer.parseInt(String.valueOf(userExt.get("flag"))));
				up.setIndexNo(userExt.get("index_no")==null?0:Integer.parseInt(String.valueOf(userExt.get("index_no"))));
				up.setLableName(userExt.get("lable_name")==null?"":String.valueOf(userExt.get("lable_name")));
				up.setParamName(userExt.get("param_name")==null?"":String.valueOf(userExt.get("param_name")));
				up.setPermission(userExt.get("permission")==null?0:Integer.parseInt(String.valueOf(userExt.get("permission"))));
				up.setType(userExt.get("type")==null?"":String.valueOf(userExt.get("type")));
				person.getUserParams().add(up);
			}
		}else{
			throw new SystemException("personNotFound");
		}
		
		page.put("person", person);
		
		return page;
	}
	
	public void updateUserLastLogin(int userId, String currentLoginIp, 
			String currentLoginTime) throws Exception{
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("userId", userId);
	    param.put("lastLoginIp", currentLoginIp);
	    param.put("lastLoginTime", currentLoginTime);
		userDAO.updateUser(param);
	}
	
	public Map updatePass(int userId, String password, String newPassword, String rePassword,String passStrength) throws Exception{
		Map res = new HashMap();
		Map user = (Map<String, Object>)userDAOQ.getUserBy("userId", String.valueOf(userId));
		if(!(DataUtils.getMD5Str(password).equalsIgnoreCase(user.get("password").toString()))){
			res.put("message", "error");
		}else{
			Map param = new HashMap();
		    param.put("nickname", user.get("nickname").toString());
		    param.put("password", DataUtils.getMD5Str(newPassword));
		    param.put("passStrength", passStrength);
			param.put("userId", String.valueOf(userId));
			userDAO.updateUser(param);
			res.put("message", "success");
		}
		return res;
	}
	
	
	public Map updateSecurityEmail(int userId, String password, String securityEmail) throws Exception{
		Map res = new HashMap();
		Map user = (Map<String, Object>)userDAOQ.getUserBy("userId", String.valueOf(userId));
		if(!(DataUtils.getMD5Str(password).equalsIgnoreCase(user.get("password").toString()))){
			res.put("message", "error");
		}else{
			Map param = new HashMap();
		    param.put("securityEmail", securityEmail);
			param.put("userId", String.valueOf(userId));
			userDAO.updateUser(param);
			res.put("message", "success");
		}
		return res;
	}
	
	
	public Map getIntegral(int userId, String getIntegral, int page) throws Exception{
		Map res = new HashMap();
		ShardedJedis jedis = jedisPool.getResource();
		try{
			XStream stream=new XStream();
			String integralSum = jedis.get(userId + "IntegralSum");
			res.put("sum", integralSum);
			long length = jedis.llen(userId + "Integrals");
			int startNum = 0;
			int endNum = -1;
			
			if(page > 0){
				if(page * Common.PNN_USER_PAGE_LIMIT < length){
					endNum = page * Common.PNN_USER_PAGE_LIMIT;
				}
				
				startNum = (page-1) * Common.PNN_USER_PAGE_LIMIT;
				
				List integrals = jedis.lrange(userId + "Integrals",startNum,endNum);
				List fintegral = new ArrayList();
				for(int i = 0; i < integrals.size(); i++){
					String str = integrals.get(i).toString();
					stream.alias("UserIntegralDTO", UserIntegralDTO.class);
					UserIntegralDTO integral = (UserIntegralDTO)stream.fromXML(str);
					fintegral.add(integral);
				}
				res.put("list", fintegral);
				res.put("page", page);
				res.put("pageCount", Math.ceil((double)fintegral.size()/(double)Common.PNN_USER_PAGE_LIMIT));
			}else{
				if(Common.PNN_USER_PAGE_LIMIT < length){
					endNum = Common.PNN_USER_PAGE_LIMIT;
				}
				List error = new ArrayList();
				res.put("list", error);
				res.put("page", page);
				res.put("pageCount", 0);
			}
			
		} catch (Exception e) {  
            //logger.error(e);  
            e.printStackTrace();  
        } finally {  
            jedisPool.returnResource(jedis);  
        } 
		
	      
		return res;
	}
}
